package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ChapterDO;
import com.jinzhi.jzweb.domain.CoursesDO;
import com.jinzhi.jzweb.domain.TrainingResourcesDO;
import com.jinzhi.jzweb.service.ChapterService;
import com.jinzhi.jzweb.service.CoursesService;
import com.jinzhi.jzweb.service.TrainingResourcesService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * <pre>
 * 培训资源表
 * </pre>
 * <small> 2020-02-24 21:00:11 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/trainingResources")
public class TrainingResourcesController extends BaseController {
	@Autowired
	private TrainingResourcesService trainingResourcesService;
	@Autowired
	private UserService userService;
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private ChapterService chapterService;

	@GetMapping()
	@RequiresPermissions("jzweb:trainingResources:trainingResources")
	String TrainingResources(){
		return "jzweb/trainingResources/trainingResources";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:trainingResources:trainingResources")
	public Result<Page<TrainingResourcesDO>> list(HttpServletRequest req, TrainingResourcesDO trainingResourcesDTO){
		Wrapper<TrainingResourcesDO> wrapper = new EntityWrapper<TrainingResourcesDO>().orderBy("id", false);
		if (trainingResourcesDTO.getState() != null){
			wrapper.eq("state",trainingResourcesDTO.getState());
		}
		if (trainingResourcesDTO.getType() != null){
			wrapper.eq("type",trainingResourcesDTO.getType());
		}
		if (trainingResourcesDTO.getName() != null){
			wrapper.like("name",trainingResourcesDTO.getName());
		}

		String strr = roleCourse(req,trainingResourcesDTO.getCoursesName());
		if (org.apache.commons.lang.StringUtils.isBlank(strr)) {
			wrapper.and();
			wrapper.eq("courses_id", null);
		} else if(!strr.equals("@#$%^&*!~")){
			wrapper.and();
			wrapper.in("courses_id", strr.substring(0, strr.length() - 1));
		}

		if (org.apache.commons.lang.StringUtils.isNotBlank(trainingResourcesDTO.getChapterName())){
			Wrapper<ChapterDO> orWrapper = new EntityWrapper<ChapterDO>().like("name",trainingResourcesDTO.getChapterName());
			List<ChapterDO>  chapterDOS = chapterService.selectList(orWrapper);
			String str = "";
			for (ChapterDO chapterDO : chapterDOS){
				str = str + chapterDO.getId() + ",";
			}
			wrapper.and();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
				wrapper.in("chapter_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("chapter_id",null);
			}
		}

		Page<TrainingResourcesDO> page = trainingResourcesService.selectPage(getPage(TrainingResourcesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			TrainingResourcesDO obj = (TrainingResourcesDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.selectById(obj.getUpdaterId());
				if (userDO != null) {
					obj.setUpdateName(userDO.getUsername());
				}
			}
			if (obj.getCoursesId() != null){
				CoursesDO coursesDO = coursesService.selectById(obj.getCoursesId());
				if (coursesDO != null) {
					obj.setCoursesName(coursesDO.getName());
				}
			}
			if (obj.getChapterId() != null){
				ChapterDO chapterDO = chapterService.selectById(obj.getChapterId());
				if (chapterDO != null) {
					obj.setChapterName(chapterDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:trainingResources:add")
	String add(){
		return "jzweb/trainingResources/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:trainingResources:edit")
	String edit(@PathVariable("id") Long id,Model model){
		TrainingResourcesDO trainingResources = trainingResourcesService.selectById(id);
		model.addAttribute("trainingResources", trainingResources);
		return "jzweb/trainingResources/edit";
	}

	@Log("添加培训资源表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:trainingResources:add")
	public Result<String> save(TrainingResourcesDO trainingResources) {
		//根据章节id、类型判断是否重复，一个章节的一种类型数据唯一
//		TrainingResourcesDO trainingResourcesDO = trainingResourcesService
//				.findOneByKv("chapter_id", trainingResources.getChapterId(), "type", trainingResources.getType());
//		if (trainingResourcesDO != null) {
//			return Result.fail("一个章节对应的资源类型唯一，目前资源类型已存在，请检查");
//		} else {
		if(trainingResources.getType()==5){
			if(trainingResources.getFileRoute()!=null) {
				boolean flag = true;
				String fileRoute = trainingResources.getFileRoute();
				boolean isURL = isURL(fileRoute);
				if(isURL){
					String[] str = fileRoute.split("/");
					String newfileName = str[str.length-1];
					//获取后缀
					String[] str2 = newfileName.split("\\.");
					if(str2.length>1) {
						String fileType = str2[1];
						System.out.println("fileType:" + fileType);
						if(fileType.equals("mp4") || fileType.equals("webm") || fileType.equals("ogg")){
							flag = true;
						}else {
							flag = false;
						}
					}else {
						flag = false;
					}
				}else {
					flag = false;
				}
				if(!flag) {
					return new Result<>(500, "请输入正确的地址!", null);
				}else {
					trainingResources.setCreaterId(this.getUserId());
					trainingResources.setUpdaterId(this.getUserId());
					boolean bbc = trainingResourcesService.insert(trainingResources);
					if (!bbc) {
						return Result.fail();
					}
					return Result.ok();
				}
			}else {
				return new Result<>(500, "请输入地址!", null);
			}
		}else {
			trainingResources.setCreaterId(this.getUserId());
			trainingResources.setUpdaterId(this.getUserId());
			boolean bbc = trainingResourcesService.insert(trainingResources);
			if (!bbc) {
				return Result.fail();
			}
			return Result.ok();
		}
		//}
	}

	public boolean isURL(String str){
		//转换为小写
		str = str.toLowerCase();
		String regex = "^((https|http)?://)"  //https、http、ftp、rtsp、mms
				//+ "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
				+ "(([0-9]{1,3}\\.){3}[0-9]{1,3}" // IP形式的URL- 例如：199.194.52.184
				+ "|" // 允许IP和DOMAIN（域名）
				+ "([0-9a-z_!~*'()-]+\\.)*" // 域名- www.
				+ "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\\." // 二级域名
				+ "[a-z]{2,6})" // first level domain- .com or .museum
				+ "(:[0-9]{1,5})?" // 端口号最大为65535,5位数
				+ "((/?)|" // a slash isn't required if there is no file name
				+ "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
		return  str.matches(regex);
	}

	@Log("修改培训资源表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:trainingResources:edit")
	public Result<String>  update( TrainingResourcesDO trainingResources){
		//根据章节id、类型判断是否重复，一个章节的一种类型数据唯一
		List<TrainingResourcesDO> trainingResourcesDOS = trainingResourcesService
				.findByKv("type", trainingResources.getType(), "chapter_id", trainingResources.getChapterId());
		if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
//			if(trainingResourcesDOS.size() == 1){
//				if(trainingResourcesDOS.get(0).getId().equals(trainingResources.getId())){
					if(trainingResources.getType()==5){
						if(trainingResources.getFileRoute()!=null) {
							boolean flag = true;
							String fileRoute = trainingResources.getFileRoute();
							boolean isURL = isURL(fileRoute);
							if(isURL){
								String[] str = fileRoute.split("/");
								String newfileName = str[str.length-1];
								//获取后缀
								String[] str2 = newfileName.split("\\.");
								if(str2.length>1) {
									String fileType = str2[1];
									System.out.println("fileType:" + fileType);
									if(fileType.equals("mp4") || fileType.equals("webm") || fileType.equals("ogg")){
										flag = true;
									}else {
										flag = false;
									}
								}else {
									flag = false;
								}
							}else {
								flag = false;
							}
							if(!flag) {
								return new Result<>(500, "请输入正确的地址!", null);
							}else {
								trainingResources.setCreaterId(this.getUserId());
								trainingResources.setUpdaterId(this.getUserId());
								boolean bbc = trainingResourcesService.insert(trainingResources);
								if (!bbc) {
									return Result.fail();
								}
								return Result.ok();
							}
						}else {
							return new Result<>(500, "请输入地址!", null);
						}
					}else {
						trainingResources.setUpdaterId(this.getUserId());
						boolean update = trainingResourcesService.updateById(trainingResources);
						return update ? Result.ok() : Result.fail();
					}
//				}
			//}
			//return Result.fail("一个章节对应的资源类型唯一，目前资源类型已存在，请检查");
		} else {
			trainingResources.setUpdaterId(this.getUserId());
			boolean update = trainingResourcesService.updateById(trainingResources);
			return update ? Result.ok() : Result.fail();
		}
	}

	@Log("删除培训资源表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingResources:remove")
	public Result<String>  remove( Long id){
		trainingResourcesService.deleteById(id);
		return Result.ok();
	}

	@Log("批量删除培训资源表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:trainingResources:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		trainingResourcesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	/**
	 * 对应课程下的章节数据
	 */
	@Log("对应课程下的章节数据")
	@GetMapping( "/chapter")
	@ResponseBody
	Result<?> chapter(Long id){
		List<ChapterDO> chapterList = chapterService.findByKv("courses_id" ,id , "state" ,0);

		return Result.ok(chapterList);
	}

}
